import { FormSchemaEntity, FormSchemaEntityField } from '@farris/designer-services';

export class ResolveTemplateFieldUtil {

    /**
     * 获取实体中的所有简单字段
     */
    getSimpleTableFieldsByBindTo(entities: FormSchemaEntity[], bindTo: string): FormSchemaEntityField[] {
        if (!entities || entities.length === 0) {
            return;
        }
        const splitIndex = bindTo.indexOf('/');
        if (splitIndex > -1) {
            bindTo = bindTo.slice(splitIndex + 1, bindTo.length);
        }

        for (const entity of entities) {
            const entityType = entity.type;
            if (!entityType) {
                return [];
            }
            if (bindTo === '' || bindTo === entity.code || bindTo === entity.label) {
                return this.extractFieldsFromEntityType(entity.type);
            }
            if (entityType.entities && entityType.entities.length > 0) {
                const fields = this.getSimpleTableFieldsByBindTo(entityType.entities, bindTo);
                if (fields) {
                    return fields;
                }
            }
        }
    }

    private extractFieldsFromEntityType(entityType: { fields?: FormSchemaEntityField[] }) {
        const fields: FormSchemaEntityField[] = [];
        if (entityType && entityType.fields && entityType.fields.length) {
            entityType.fields.forEach(field => {
                if (field.$type === 'SimpleField') {
                    fields.push(field);
                } else {
                    const extractedFields = this.extractFieldsFromEntityType(field.type);
                    if (extractedFields.length) {
                        extractedFields.forEach(extractedField => fields.push(extractedField));
                    }
                }
            });
        }
        return fields;
    }
}
